import { connect } from 'umi';
import styles from './index.less';
import { Table, Radio, Select, Input, Tooltip, InputNumber } from 'antd';
import { question } from '@/assets';
import { TradeStrategy, SubmitType } from '@/pages/Tianji/TenDaysCentralizedBidding/constant.js';
import { tableLocale } from '@/tool/components/PageEmpty';
const { Column, ColumnGroup } = Table;
const { Option } = Select;

function TradeTable({ currentProgramInfo, selectedRowKeys, maxValue, is_SD, dispatch }) {
  // 修改申报类型
  const changeSubmitType = (type, index) => {
    let data = JSON.parse(JSON.stringify(currentProgramInfo));
    data.hourOrderInfoList[index].submitType = type;
    data.hourOrderInfoList[index].firstSubmitPower = 0;
    dispatch({
      type: 'tenDaysCentralizedBidding/editProgramInfoEffect',
      payload: data,
    });
  };

  // 修改第一段申报电量
  const changeFirstSubmitPower = (value, index, type) => {
    let data = JSON.parse(JSON.stringify(currentProgramInfo));
    data.hourOrderInfoList[index].firstSubmitPower = value;
    dispatch({
      type: 'tenDaysCentralizedBidding/editProgramInfoEffect',
      payload: data,
    });
  };

  // 修改第一段申报电价
  const changeFirstPrice = (value, index) => {
    let data = JSON.parse(JSON.stringify(currentProgramInfo));
    data.hourOrderInfoList[index].firstPrice = value;
    data.hourOrderInfoList[index].secondPrice = value;
    dispatch({
      type: 'tenDaysCentralizedBidding/editProgramInfoEffect',
      payload: data,
    });
  };

  // 修改第二段申报电价
  const changeSecondPrice = (value, index) => {
    let data = JSON.parse(JSON.stringify(currentProgramInfo));
    data.hourOrderInfoList[index].secondPrice = value;
    dispatch({
      type: 'tenDaysCentralizedBidding/editProgramInfoEffect',
      payload: data,
    });
  };

  // 修改交易方向
  const changeTradeStrategy = (value, index) => {
    let data = JSON.parse(JSON.stringify(currentProgramInfo));
    let item = data.hourOrderInfoList[index];
    item.tradeStrategy = value;
    if (item.tradeStrategy === TradeStrategy.SELL || item.tradeStrategy === TradeStrategy.BUY) {
      // 如果价格在限价范围之外，则设置为最低价
      if (item.firstPrice > item.upperPrice || item.firstPrice < item.lowerPrice) {
        item.firstPrice = item.lowerPrice;
      }
      if (item.secondPrice > item.upperPrice || item.secondPrice < item.lowerPrice) {
        item.secondPrice = item.lowerPrice;
      }
    }
    dispatch({
      type: 'tenDaysCentralizedBidding/editProgramInfoEffect',
      payload: data,
    });
  };

  return (
    <Table
      className={styles.tradeTable}
      dataSource={currentProgramInfo.hourOrderInfoList}
      locale={tableLocale}
      pagination={false}
      rowSelection={{
        type: 'checkbox',
        selectedRowKeys: selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          dispatch({
            type: 'tenDaysCentralizedBidding/setSelectedRowKeys',
            payload: selectedRowKeys,
          });
        },
      }}
      bordered={true}
      rowKey="hourOrder"
      scroll={{ x: 1750 }}
      rowClassName={(record) => {
        let classStr;
        switch (record.tradeStrategy) {
          case TradeStrategy.SELL:
            classStr = 'red';
            break;
          case TradeStrategy.BUY:
            classStr = 'green';
            break;
          case TradeStrategy.NOT_DEAL:
            classStr = 'yellow';
            break;
          case TradeStrategy.NO_STRATEGY:
            classStr = 'gray';
            break;
        }
        return classStr;
      }}
    >
      <Column
        align="center"
        title={!is_SD ? '时点' : '日期'}
        dataIndex="hourOrder"
        key="hourOrder"
        fixed="left"
        width={100}
      />
      <Column
        align="center"
        fixed="left"
        width={200}
        title={
          <div>
            <div>
              <span>交易方向</span>
              <Tooltip
                placement="bottom"
                title={
                  <span>
                    交易策略分为四种，分别代表“卖出”(红色)、“不交易”(黄色)、“买入”(绿色)
                    {!is_SD ? '、“无策略”(灰色)' : ''}。
                    <br />
                    其中“不交易”代表该时点的策略是“不想参与交易”，如申报时交易中心已有挂单，则会做撤单操作；
                    {!is_SD
                      ? '“无策略”代表方案不对该时点设定策略，申报时不改变交易平台当前申报状态，请注意区分二者'
                      : ''}
                    。
                  </span>
                }
              >
                <img className={styles.icon} src={question} />
              </Tooltip>
            </div>
            <div>(卖出、不交易、买入{!is_SD ? '、无策略' : ''})</div>
          </div>
        }
        dataIndex="tradeStrategy"
        key="tradeStrategy"
        render={(text, record, index) => (
          <div className={styles.tradeStrategy}>
            <Radio.Group
              className={styles.radioGroup}
              value={text}
              onChange={(e) => {
                changeTradeStrategy(e.target.value, index);
              }}
            >
              <Radio.Button className={`${styles.radio} red`} value={TradeStrategy.SELL}>
                <div className="circle" />
              </Radio.Button>
              <Radio.Button className={`${styles.radio} yellow`} value={TradeStrategy.NOT_DEAL}>
                <div className="circle" />
              </Radio.Button>
              <Radio.Button className={`${styles.radio} green`} value={TradeStrategy.BUY}>
                <div className="circle" />
              </Radio.Button>
              {!is_SD ? (
                <Radio.Button className={`${styles.radio} gray`} value={TradeStrategy.NO_STRATEGY}>
                  <div className="circle" />
                </Radio.Button>
              ) : (
                ''
              )}
            </Radio.Group>
          </div>
        )}
      />
      <Column
        align="center"
        title={
          <div>
            <div>价格上限</div>
            <div>(元/MWh)</div>
          </div>
        }
        dataIndex="upperPrice"
        key="upperPrice"
        render={(text) => <>{text?.toFixed(2) || '-'}</>}
      />
      <Column
        align="center"
        title={
          <div>
            <div>价格下限</div>
            <div>(元/MWh)</div>
          </div>
        }
        dataIndex="lowerPrice"
        key="lowerPrice"
        render={(text) => <>{text?.toFixed(2) || '-'}</>}
      />
      {!is_SD ? (
        <Column
          align="center"
          title={
            <div>
              <div>
                <span>买入限额</span>
                <Tooltip
                  placement="bottom"
                  title="展示方案全部交易单元在各个时点的买入限额总和。该限额仅做展示用，申报电量的限额控制仍以各单元限额为准。"
                >
                  <img className={styles.icon} src={question} />
                </Tooltip>
              </div>
              <div>(MWh)</div>
            </div>
          }
          dataIndex="buyLimit"
          key="buyLimit"
          render={(text) => <>{text?.toFixed(3) || '-'}</>}
        />
      ) : (
        ''
      )}
      {!is_SD ? (
        <Column
          align="center"
          title={
            <div>
              <div>
                <span>卖出限额</span>
                <Tooltip
                  placement="bottom"
                  title="展示方案全部交易单元在各个时点的卖出限额总和。该限额仅做展示用，申报电量的限额控制仍以各单元限额为准。"
                >
                  <img className={styles.icon} src={question} />
                </Tooltip>
              </div>
              <div>(MWh)</div>
            </div>
          }
          dataIndex="sellLimit"
          key="sellLimit"
          render={(text) => <>{text?.toFixed(3) || '-'}</>}
        />
      ) : (
        ''
      )}
      <ColumnGroup
        title={
          <>
            <span>{!is_SD ? '段一申报电量' : '申报电量'}</span>
            <Tooltip
              placement="bottom"
              title="该申报电量为针对每个交易单元的时点申报值，非多交易单元总申报量。请注意与限额数据做区分"
            >
              <img className={styles.icon} src={question} />
            </Tooltip>
          </>
        }
      >
        <Column
          align="center"
          title="参考值"
          dataIndex="submitType"
          key="submitType"
          render={(text, record, index) => (
            <div className={styles.submitType}>
              <Radio
                checked={text === SubmitType.INSTALLED_CAPACITY || text === SubmitType.TRADE_LIMIT}
                onChange={() => changeSubmitType(SubmitType.INSTALLED_CAPACITY, index)}
              />
              <Select
                value={text === SubmitType.FIXED ? SubmitType.INSTALLED_CAPACITY : text}
                bordered={false}
                onChange={(type) => changeSubmitType(type, index)}
                disabled={text === SubmitType.FIXED}
                showArrow={!is_SD}
              >
                <Option className={styles.submitTypeOption} value={SubmitType.INSTALLED_CAPACITY}>
                  装机容量
                </Option>
                {!is_SD ? (
                  <Option className={styles.submitTypeOption} value={SubmitType.TRADE_LIMIT}>
                    交易限额
                  </Option>
                ) : (
                  ''
                )}
              </Select>
            </div>
          )}
        />
        <Column
          align="center"
          title="比例(%)"
          dataIndex="firstSubmitPower"
          key="firstSubmitPower"
          render={(text, record, index) => (
            <InputNumber
              min={0}
              max={is_SD ? 100 : 50}
              precision={0}
              className={styles.input}
              value={
                record.submitType === SubmitType.INSTALLED_CAPACITY ||
                record.submitType === SubmitType.TRADE_LIMIT
                  ? text * 100
                  : 0
              }
              onChange={(value) => {
                changeFirstSubmitPower(value / 100, index);
              }}
              disabled={record.submitType === SubmitType.FIXED}
            />
          )}
        />
        <Column
          align="center"
          title="固定值(MWh)"
          dataIndex="submitType"
          key="submitType"
          render={(text, record, index) => {
            return (
              <div className={styles.submitType}>
                <Radio
                  checked={text === SubmitType.FIXED}
                  onChange={() => changeSubmitType(SubmitType.FIXED, index)}
                />
                <InputNumber
                  min={0}
                  max={is_SD ? maxValue : Number.MAX_SAFE_INTEGER}
                  precision={3}
                  className={styles.input}
                  value={text === SubmitType.FIXED ? record.firstSubmitPower : 0}
                  onChange={(value) => {
                    const v = is_SD ? Math.floor(value / 10) * 10 : value;
                    changeFirstSubmitPower(v, index);
                  }}
                  disabled={
                    record.submitType === SubmitType.INSTALLED_CAPACITY ||
                    record.submitType === SubmitType.TRADE_LIMIT
                  }
                />
              </div>
            );
          }}
        />
      </ColumnGroup>
      <Column
        align="center"
        title={
          <div>
            <div>{!is_SD ? '段一申报电价' : '申报电价'}</div>
            <div>(元/MWh)</div>
          </div>
        }
        dataIndex="firstPrice"
        key="firstPrice"
        render={(text, record, index) => (
          <InputNumber
            min={
              record.tradeStrategy === TradeStrategy.SELL ||
              record.tradeStrategy === TradeStrategy.BUY
                ? record.lowerPrice
                : 0
            }
            max={
              record.tradeStrategy === TradeStrategy.SELL ||
              record.tradeStrategy === TradeStrategy.BUY
                ? record.upperPrice
                : Number.MAX_SAFE_INTEGER
            }
            precision={2}
            className={styles.input}
            value={text}
            onChange={(value) => {
              changeFirstPrice(value, index);
            }}
          />
        )}
      />
      {!is_SD ? (
        <ColumnGroup title="段二申报电量">
          <Column
            align="center"
            title="参考值"
            dataIndex="submitType"
            key="submitType"
            render={(text, record, index) => (
              <div className={styles.submitType}>
                <Radio
                  checked={
                    text === SubmitType.INSTALLED_CAPACITY || text === SubmitType.TRADE_LIMIT
                  }
                  disabled={true}
                />
                <Select
                  value={text === SubmitType.FIXED ? SubmitType.INSTALLED_CAPACITY : text}
                  bordered={false}
                  disabled={true}
                >
                  <Option className={styles.submitTypeOption} value={SubmitType.INSTALLED_CAPACITY}>
                    装机容量
                  </Option>
                  <Option className={styles.submitTypeOption} value={SubmitType.TRADE_LIMIT}>
                    交易限额
                  </Option>
                </Select>
              </div>
            )}
          />
          <Column
            align="center"
            title="比例(%)"
            dataIndex="firstSubmitPower"
            key="firstSubmitPower"
            render={(text, record, index) => (
              <Input
                className={styles.input}
                value={
                  record.submitType === SubmitType.INSTALLED_CAPACITY ||
                  record.submitType === SubmitType.TRADE_LIMIT
                    ? text * 100
                    : 0
                }
                disabled={true}
                precision={0}
              />
            )}
          />
          <Column
            align="center"
            title="固定值(MWh)"
            dataIndex="submitType"
            key="submitType"
            render={(text, record, index) => (
              <div className={styles.submitType}>
                <Radio checked={text === SubmitType.FIXED} disabled={true} />
                <Input
                  className={styles.input}
                  value={text === SubmitType.FIXED ? record.firstSubmitPower : 0}
                  disabled={true}
                />
              </div>
            )}
          />
        </ColumnGroup>
      ) : (
        ''
      )}
      {!is_SD ? (
        <Column
          align="center"
          title={
            <div>
              <div>{!is_SD ? '段二申报电价' : '申报状态'}</div>
              <div>(元/MWh)</div>
            </div>
          }
          dataIndex="secondPrice"
          key="secondPrice"
          render={(text, record, index) => (
            <InputNumber
              min={
                record.tradeStrategy === TradeStrategy.SELL ||
                record.tradeStrategy === TradeStrategy.BUY
                  ? record.lowerPrice
                  : 0
              }
              max={
                record.tradeStrategy === TradeStrategy.SELL ||
                record.tradeStrategy === TradeStrategy.BUY
                  ? record.upperPrice
                  : Number.MAX_SAFE_INTEGER
              }
              precision={2}
              className={styles.input}
              value={text}
              onChange={(value) => {
                changeSecondPrice(value, index);
              }}
            />
          )}
        />
      ) : (
        ''
      )}
      <Column
        align="center"
        width={140}
        title={
          <>
            <div>
              <span>申报总电量</span>
              <Tooltip
                placement="bottomRight"
                title="展示本方案对应时点两段申报的电量总和。当申报方案为比例时，则展示两段申报的策略描述。注意，这里是对方案的描述，各个交易单元的具体数值可能不同。"
              >
                <img className={styles.icon} src={question} />
              </Tooltip>
            </div>
            <div>(MWh)</div>
          </>
        }
        dataIndex="totalPower"
        key="totalPower"
        render={(text, record, index) => {
          let ele;
          switch (record.submitType) {
            case SubmitType.FIXED:
              ele = <div>{(record.firstSubmitPower * (is_SD ? 1 : 2)).toFixed(3)}</div>;
              break;
            case SubmitType.INSTALLED_CAPACITY:
              ele = (
                <div>装机容量 * {Math.round(record.firstSubmitPower * 100 * (is_SD ? 1 : 2))}%</div>
              );
              break;
            case SubmitType.TRADE_LIMIT:
              ele = (
                <div>交易限额 * {Math.round(record.firstSubmitPower * 100 * (is_SD ? 1 : 2))}%</div>
              );
              break;
          }
          return ele;
        }}
      />
    </Table>
  );
}

export default connect(({ tenDaysCentralizedBidding }) => ({
  currentProgramInfo: tenDaysCentralizedBidding.currentProgramInfo,
  selectedRowKeys: tenDaysCentralizedBidding.selectedRowKeys,
  maxValue: tenDaysCentralizedBidding.maxValue,
}))(TradeTable);
